###
# -*- coding: utf-8 -*-
# 对扫流的流速记录数据进行可视化，绘制时间与流速关系图，并在指定流速处绘制虚线，标记交点。

###
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import numpy as np

# 设置中文字体为宋体，英文字体为Times New Roman
# 检查系统是否安装宋体和Times New Roman，如果没有则需要手动安装或指定其他字体
try:
    song_font = fm.FontProperties(fname='C:/Windows/Fonts/simsun.ttc') # 宋体
except:
    song_font = fm.FontProperties(family='SimSun') # Fallback to generic SimSun if path fails

try:
    times_font = fm.FontProperties(family='Times New Roman')
except:
    times_font = fm.FontProperties(family='serif') # Fallback to generic serif if Times New Roman fails

plt.rcParams['font.sans-serif'] = [song_font.get_name()] # 设置全局中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
plt.rcParams['font.family'] = times_font.get_name() # 设置全局英文字体和数字字体

# 数据文件路径
file_path = "F:/wry/扫流流速记录.xlsx"

# 读取Excel文件
try:
    df = pd.read_excel(file_path)
except FileNotFoundError:
    print(f"错误：文件 '{file_path}' 未找到。请检查文件路径。")
    exit()
except Exception as e:
    print(f"读取Excel文件时发生错误：{e}")
    exit()

# 确保列名正确
if 'time' not in df.columns or '流速' not in df.columns:
    print("错误：Excel文件中缺少 'time' 或 '流速' 列。")
    exit()

time_data = df['time']
flow_speed_data = df['流速']

# 创建图表
plt.figure(figsize=(12, 7))
plt.plot(time_data, flow_speed_data, label='流速数据', color='blue')

# 定义虚线Y轴值和颜色
horizontal_lines_y = [0.6, 2.0, 3.0, 4.1, 5.0]
colors = ['red', 'green', 'purple', 'orange', 'brown']
line_styles = ['--', '--', '--', '--', '--']

# 绘制虚线并标记交点
for i, y_val in enumerate(horizontal_lines_y):
    # 绘制水平虚线
    plt.axhline(y=y_val, color=colors[i], linestyle=line_styles[i], linewidth=1.5, label=f'Y={y_val} 虚线')

    # 寻找交点或最近点
    intersections_x = []
    intersections_y = []
    
    # 线性插值找到精确交点
    for j in range(len(time_data) - 1):
        x1, y1 = time_data.iloc[j], flow_speed_data.iloc[j]
        x2, y2 = time_data.iloc[j+1], flow_speed_data.iloc[j+1]

        # 检查线段是否与水平线相交
        if (y1 <= y_val < y2) or (y2 <= y_val < y1):
            if y2 - y1 != 0:
                x_intersect = x1 + (x2 - x1) * (y_val - y1) / (y2 - y1)
                intersections_x.append(x_intersect)
                intersections_y.append(y_val)
            elif y1 == y_val:
                intersections_x.append(x1)
                intersections_y.append(y_val)
    
    # 如果没有找到交点，则找到离该流速最近的数据点
    if not intersections_x:
        closest_idx = np.abs(flow_speed_data - y_val).argmin()
        intersections_x.append(time_data.iloc[closest_idx])
        intersections_y.append(flow_speed_data.iloc[closest_idx]) # 使用实际数据点的Y值

    # 标记交点并绘制垂直虚线和标注坐标
    for x_int, y_int in zip(intersections_x, intersections_y):
        plt.plot(x_int, y_int, 'o', color=colors[i], markersize=6) # 标记交点，不添加到图例
        plt.axvline(x=x_int, color=colors[i], linestyle=':', linewidth=1.5) # 绘制垂直虚线，粗细与水平虚线一致
        
        # 标注交点坐标
        plt.text(x_int + 0.5, y_int, f'({x_int:.2f}, {y_int:.1f})', 
                 color=colors[i], fontproperties=times_font, fontsize=9,
                 verticalalignment='bottom', horizontalalignment='left')

# 设置图表属性
plt.title('时间与流速关系图', fontproperties=song_font)
plt.xlabel('时间', fontproperties=song_font)
plt.ylabel('流速', fontproperties=song_font)
plt.grid(True, linestyle='--', alpha=0.7) # 添加网格线

# 设置边框和刻度线朝内
plt.tick_params(axis='both', direction='in', length=6, width=1.5, colors='black',
                grid_color='gray', grid_alpha=0.5, labelsize=10)

# 设置刻度数字字体为Times New Roman
for label in plt.gca().get_xticklabels():
    label.set_fontproperties(times_font)
for label in plt.gca().get_yticklabels():
    label.set_fontproperties(times_font)

plt.legend(prop=song_font) # 显示图例，并设置字体
plt.tight_layout() # 调整布局，避免标签重叠
plt.show()
